// pages/linghongbao/linghongbao.js
var util= require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    interval: 5500,
    duration: 1500,
    youhuiquanPutong:false,//普通优惠券发放中的
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCouponsMarket()
    
    var cu = [{
      "preferentialamount":2,
      "moneyHreshold":2,
      "couponname":"优惠券1",
      "youxiaoqi":"7",
      "lingquStatus":1
    },
    {
      "preferentialamount":2,
      "moneyHreshold":2,
      "couponname":"满2元可用",
      "youxiaoqi":"7",
      "lingquStatus":1
    }]
//     this.setData({
// youhuiquanPutong:cu
// })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  toyouhuiquan:function(){
    wx.navigateTo({
      url: '../ucenter/mycoupons/index',
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //查询有效发放的优惠券
  getCouponsMarket(){
    let that =this
    that.setData({
      youhuiquanPutong:false//置空数据
    })
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getcouponMarket',
      // 传给云函数的参数
      data: {
       
      },
    })
    .then(res => {
      let coupon = res.result.data
        let putongcoupon =[]
        if(coupon.length>0){
          
          for (let dex = 0; dex < coupon.length; dex++) {
            const element = coupon[dex];
            if(element.leixing==2){
             
             
            }else{
              putongcoupon.push(element)
              that.setData({
                youhuiquanPutong:putongcoupon
              })
            }
          }
          
          
      }
     
    })
  },
  lingquyouhuiquan(e){
    var that =this
    let  id = e.currentTarget.dataset.id;
    const db = wx.cloud.database()
    db.collection('coupons').add({
      data: {
        dateAdd:new Date(), 
        couponsMarketid:id,
        dateEnd: util.getdeadline( e.currentTarget.dataset.youxiaoqi),
        money: e.currentTarget.dataset.preferentialamount,
        moneyHreshold: e.currentTarget.dataset.moneyhreshold,
        name: e.currentTarget.dataset.couponname,
        status: 0,
      },
      success: function(res) {
        wx.showModal({
          title: '提示',
          content: '已成功领取优惠券',
        })
       //再查优惠券
        that.getCouponsMarket()
        
      },
      fail: err => {
          console.log(err)
      }
    })
  },
})